package com.ezops.poc.aggregation;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ezops.poc.bo.ClientTradeModel;
import com.ezops.trade.processing.partners.orchestrade.OrchesTradeModel;

public class EzopsAggregationStrategy implements AggregationStrategy {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(EzopsAggregationStrategy.class);

	@Override
	public Exchange aggregate(Exchange exchange, Exchange exchange2) {

		if (exchange == null) {
			return shouldProceed(exchange2) ? exchange2 : null;
		}

		LOGGER.debug("\n Old Exchage Order: "
				+ exchange.getIn().getBody(String.class));
		LOGGER.debug("\n New Exchnge Order: "
				+ exchange2.getIn().getBody(String.class));

		if (shouldProceed(exchange2)) {
			if (exchange.getIn().getBody() instanceof List) {

				final List convertedTrades = exchange.getIn().getBody(
						List.class);
				convertedTrades.add(exchange2.getIn().getBody());
				exchange.getIn().setBody(convertedTrades);
			} else {
				final List convertedTrades = new ArrayList<>();
				convertedTrades.add(exchange2.getIn().getBody());
				convertedTrades.add(exchange.getIn().getBody());
				exchange.getIn().setBody(convertedTrades);

			}
		}
		return exchange;
	}

	/**
	 * After split some exchange routes are stopped (like activiti task) but
	 * they are still coming til the aggregator. As of now just skip those.
	 * 
	 * @param newExchange
	 * @return
	 */
	private boolean shouldProceed(Exchange newExchange) {

		if ((newExchange.getIn().getBody() instanceof ClientTradeModel)
				|| (newExchange.getIn().getBody() instanceof OrchesTradeModel)) {
			return true;
		}
		return false;
	}
}
